package com.lyn.solitude.pluginhost.manager

import android.app.Application
import android.util.Log
import com.lyn.solitude.pluginhost.andserver.AndServer
import com.lyn.solitude.pluginhost.andserver.Server
import com.lyn.solitude.pluginhost.andserver.util.NetUtils
import com.lyn.solitude.pluginhost.andserver.website.AssetsWebsite
import com.lyn.solitude.pluginhost.handler.andserver.AndServerInterceptor
import com.lyn.solitude.pluginhost.handler.andserver.InstallPluginRequestHandler
import com.lyn.solitude.pluginhost.liveData.LiveDataManager
import com.lyn.solitude.pluginhost.uitls.NetworkUtil
import java.lang.Exception
import java.util.concurrent.TimeUnit

/**
 * @author longyn 2024/5/26
 * @version 1.0.0
 */
object AndServerManager : NetworkUtil.NetworkListener {

    const val TAG = "AndServerManager"

    lateinit var application: Application
    private var server: Server? = null

    fun initialize(application: Application) {
        if (this::application.isInitialized) {
            return
        }
        this.application = application
        server = AndServer.serverBuilder()
            .port(8080)
            .website(AssetsWebsite(application.assets, "web"))
            .inetAddress(NetUtils.getLocalIPAddress())
            .timeout(6, TimeUnit.SECONDS)
            .interceptor(AndServerInterceptor())
            .registerHandler("/installPlugin", InstallPluginRequestHandler())
            .listener(object : Server.ServerListener {
                override fun onStarted() {
                    val hostAddress = NetUtils.getLocalIPAddress().hostAddress
                    Log.d(TAG, "andServer onStarted:$hostAddress")
                    LiveDataManager.address.postValue("http://$hostAddress:8080")
                }

                override fun onStopped() {
                    Log.d(TAG, "andServer onStopped")
                }

                override fun onError(e: Exception?) {
                    e?.printStackTrace()
                    Log.d(TAG, "andServer onError")
                }

            })
            .build()
        NetworkUtil.setNetworkListener(this)
        start()
    }

    private fun start() {
        server?.startup()
    }

    private fun stop() {
        server?.shutdown()
    }

    override fun onChange(enabled: Boolean) {
        stop()
        start()
        if (enabled){
            val hostAddress = NetUtils.getLocalIPAddress().hostAddress
            LiveDataManager.address.postValue("http://$hostAddress:8080")
        }else{
            LiveDataManager.address.postValue("")
        }
    }

    override fun onMs(ms: Long) {
    }
}